package com.novellotus.iov.carvice.fragment;


import android.Manifest;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.jakewharton.rxbinding2.view.RxView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.activity.MapChargeStationActivity;
import com.novellotus.iov.carvice.adapter.CarFragmentAdapter;
import com.novellotus.iov.carvice.bean.MqttVehicleBean;
import com.novellotus.iov.carvice.bean.RxCarListBean;
import com.novellotus.iov.carvice.model.CarViewPagerModel;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.novellotus.iov.carvice.view.TipsDialog;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * fragment控制
 */
public class CarViewpagerFragment extends BaseFragment implements ViewPager.OnPageChangeListener, BaseCarFragment.CarFragmentInterface, TipsDialog.ClickTipsInterface {

    @BindView(R.id.viewpager)
    ViewPager viewPager;
    @BindView(R.id.ln_point)
    LinearLayout ln_point;
    @BindView(R.id.rlt_navigation)
    RelativeLayout rlt_navigation;
    public CarSwitchInterface carSwitchInterface;
    CarFragmentAdapter carFragmentAdapter;
    public CarViewPagerModel carViewPagerModel;
    public int current;
    private TipsDialog tipsDialog;
    RxPermissions rxPermissions;
    private boolean isCancel;

    public CarViewpagerFragment() {
        // Required empty public constructor
    }


    @Override
    View initRootView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_car_statue, container, false);
    }


    @Override
    void init() {
        rxPermissions = new RxPermissions(getActivity());
        tipsDialog = new TipsDialog(getContext());
        carViewPagerModel = new CarViewPagerModel(this, carFragmentAdapter, carSwitchInterface, this);
        if (records != null) {
            carViewPagerModel.setFragmentList(getChildFragmentManager(), viewPager, records);
            carViewPagerModel.addPoint(ln_point, records.size());
            carSwitchInterface.ChangePlate(records.get(0).getPn());
        }
        viewPager.setOffscreenPageLimit(5);
        viewPager.addOnPageChangeListener(this);
        setNavigation();
    }


    /**
     * 初始化fragment
     */
    List<RxCarListBean.RecordsBean> records;

    public void initFragment(List<RxCarListBean.RecordsBean> records) {
        this.records = records;

    }

    /**
     * 刷新Viewpager
     */
    public void updateViewpager(List<RxCarListBean.RecordsBean> records) {
        this.records = records;
        if (carViewPagerModel.isUpdate(records)) {
            carViewPagerModel.updateFragmentList(records);
            ln_point.removeAllViews();
            carViewPagerModel.addPoint(ln_point, records.size());
            carViewPagerModel.pageChange(current);
        }
    }


    /**
     * @param mqttVehicleBean 刷新mqtt数据
     */
    public void updateSinglePager(MqttVehicleBean mqttVehicleBean, String vin, int carType, int carDetailType) {
        carViewPagerModel.updateMqtt(mqttVehicleBean, vin, carType, carDetailType);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof CarViewpagerFragment.CarSwitchInterface) {
            carSwitchInterface = (CarViewpagerFragment.CarSwitchInterface) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        carSwitchInterface = null;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        current = position;
        carViewPagerModel.pageChange(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @OnClick(R.id.rlt_cancel)
    void cancel() {
        isCancel = true;
        tipsDialog.initDialog("取消关注", "取消关注本车后将无法查看该辆车数据，确定取消关注本车吗?", this);
        tipsDialog.button.setText("确定");
        tipsDialog.show();
    }


    @OnClick(R.id.rlt_add_service)
    void addService() {
//        isCancel = false;
//              tipsDialog = new TipsDialog(getActivity());
//        tipsDialog.initDialog("提示", "运维模块暂未开放,敬请期待!", this);
//        tipsDialog.button.setText("知道了");
//        tipsDialog.show();
        if (carViewPagerModel.getCurrentFragment() != null) {
            final String plate = carViewPagerModel.getCurrentFragment().getPlate().replace(" ", "");
            final String vin = carViewPagerModel.getCurrentFragment().getVin();
//            Call<ResponseBody> call = RetrofitFactory.getInstance().checkCar(plate, SharedPreferencesUtils.getKey(getContext())[0]);
//            call.enqueue(new Callback<ResponseBody>() {
//                @Override
//                public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
//
//                    try {
//                        JSONObject obj = new JSONObject(response.body().string());
//                        if (obj.getInt("code") == 200) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString("plate", plate);
//                            bundle.putString("vin", vin);
//                            String slat = obj.getJSONObject("data").getString("lat");
//                            String slng = obj.getJSONObject("data").getString("lng");
//                            double d1 = 0;
//                            if (!slat.equals("null") && slat.length() > 0) {
//                                d1 = Double.valueOf(slat);
//                            }
//                            double d2 = 0;
//                            if (!slng.equals("null") && slng.length() > 0) {
//                                d2 = Double.valueOf(slng);
//                            }
//                            bundle.putDouble("lat", d1);
//                            bundle.putDouble("lng", d2);
//                            bundle.putString("address", "");
//                            openActivity(getActivity(), AddServiceActivity.class, bundle);
//
//                        } else if (obj.getInt("code") == 427) {
//
//                            Bundle bundle = new Bundle();
//                            bundle.putString("fid", obj.getString("data"));
//                            bundle.putString("plate", plate);
//                            bundle.putString("vin", vin);
//                            openActivity(getActivity(), TaskDetailActivity.class, bundle);
//                        } else {
//                            MyUtils.showToast(getContext(), obj.getString("msg"));
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//
//                @Override
//                public void onFailure(Call<ResponseBody> call, Throwable t) {
//                    MyUtils.showToast(getActivity(), t.toString());
//                }
//            });
//            Observable<BaseEntity<RxCarCheckBean>> observable = RetrofitFactory.getInstance().checkCar(carViewPagerModel.getCurrentFragment().getPlate().replace(" ", ""), SharedPreferencesUtils.getKey(getContext())[0]);
//            observable.compose(RxSchedulers.<BaseEntity<RxCarCheckBean>>compose())
//                    .subscribe(new BaseObserver<RxCarCheckBean>(getActivity()) {
//                        @Override
//                        public void onSuccess(RxCarCheckBean response) {
//                            MyUtils.logInformation("车牌:"+carViewPagerModel.getCurrentFragment().getPlate().replace(" ", ""));
//                            Bundle bundle = new Bundle();
//                            bundle.putString("plate", carViewPagerModel.getCurrentFragment().getPlate().replace(" ", ""));
//                            bundle.putString("vin", carViewPagerModel.getCurrentFragment().getVin());
//                            bundle.putDouble("lat", response.getLat());
//                            bundle.putDouble("lng", response.getLng());
//                            openActivity(getActivity(), AddServiceActivity.class, bundle);
//                        }
//
//                        @Override
//                        public void onFail(int code, String msg) {
//                            MyUtils.showToast(getActivity(), msg);
//                        }
//
//                        @Override
//                        public void onError(String msg) {
//                            MyUtils.showToast(getActivity(), msg);
//                        }
//                    });
        }
    }

    /**
     * 导航之前先检查权限
     */

    void setNavigation() {
        RxView.clicks(rlt_navigation)
                .compose(rxPermissions.ensureEach(Manifest.permission.ACCESS_FINE_LOCATION))
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            openActivity(getActivity(), MapChargeStationActivity.class);
                        } else {
                            MyUtils.showToast(getActivity(), "定位权限已经被禁止，请到设置中允许相关权限");
                        }

                    }
                });
    }

    @Override
    public void loadStatue(int statue) {

    }

    @Override
    public void clickTipsButton() {
        if (isCancel) {
            Observable<BaseEntity<Boolean>> observable = RetrofitFactory.getInstance().cancelFollowVehicle(carViewPagerModel.getVin(current), SharedPreferencesUtils.getKey(getContext())[0]);
            observable.compose(RxSchedulers.<BaseEntity<Boolean>>compose())
                    .subscribe(new BaseObserver<Boolean>(getContext()) {
                        @Override
                        public void onSuccess(Boolean response) {
                            MyUtils.showToast(getContext(), "取消关注成功!");
                            //刷新数据
                            carSwitchInterface.UpdateCar();
                        }

                        @Override
                        public void onFail(int code, String msg) {
                            MyUtils.showToast(getContext(), msg);
                        }

                        @Override
                        public void onError(String msg) {
                            MyUtils.showToast(getContext(), msg);
                        }
                    });
        }
        tipsDialog.dismiss();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public interface CarSwitchInterface {
        void ChangePlate(String s);

        void UpdateCar();
    }
}
